from xml.dom.minidom import parse
 
# 解析 XML 文件
dom_tree = parse("books.xml")
library = dom_tree.documentElement

# 获取所有 <book> 元素
books = library.getElementsByTagName("book")
for book in books:
    print(f"\nBook ID: {book.getAttribute('id')}")
    print(f"Title: {book.getElementsByTagName('title')[0].childNodes[0].data}")
    print(f"Author: {book.getElementsByTagName('author')[0].childNodes[0].data}")
    print(f"Year: {book.getElementsByTagName('year')[0].childNodes[0].data}")

from xml.dom.minidom import Document
 
# 创建文档对象
doc = Document()
 
# 创建根元素
library = doc.createElement("library")
doc.appendChild(library)
 
# 创建书籍元素
book = doc.createElement("book")
book.setAttribute("id", "1")
library.appendChild(book)
 
# 添加子元素
title = doc.createElement("title")
title.appendChild(doc.createTextNode("Python Programming"))
book.appendChild(title)
 
author = doc.createElement("author")
author.appendChild(doc.createTextNode("John Doe"))
book.appendChild(author)
 
year = doc.createElement("year")
year.appendChild(doc.createTextNode("2023"))
book.appendChild(year)
 
# 保存为 XML 文件
with open("new_books.xml", "w") as f:
    f.write(doc.toprettyxml(indent="  "))